// utils/dictionary-api.js - Dictionary API工具类

class DictionaryAPI {
  constructor() {
    this.apiUrl = 'https://api.dictionaryapi.dev/api/v2/entries/en';
  }

  // 查询单词信息
  searchWord(word) {
    return new Promise((resolve, reject) => {
      if (!word || typeof word !== 'string') {
        reject(new Error('请提供有效的单词'));
        return;
      }

      wx.request({
        url: `${this.apiUrl}/${encodeURIComponent(word)}`,
        method: 'GET',
        success: (res) => {
          console.log('Dictionary API响应:', res.data);
          
          if (res.statusCode === 200 && res.data && res.data.length > 0) {
            try {
              const wordData = this.parseDictionaryResponse(res.data, word);
              resolve(wordData);
            } catch (error) {
              console.error('解析Dictionary API响应失败:', error);
              reject(new Error('数据解析失败'));
            }
          } else {
            reject(new Error('未找到该单词'));
          }
        },
        fail: (err) => {
          console.error('Dictionary API请求失败:', err);
          reject(new Error('网络请求失败'));
        }
      });
    });
  }

  // 解析Dictionary API响应
  parseDictionaryResponse(data, word) {
    const entry = data[0]; // 取第一个条目
    
    // 基础信息
    const wordInfo = {
      word: entry.word || word,
      phonetic: this.extractPhonetic(entry),
      audioUrl: this.extractAudioUrl(entry),
      meanings: this.extractMeanings(entry),
      etymology: this.extractEtymology(entry),
      synonyms: this.extractSynonyms(entry),
      antonyms: this.extractAntonyms(entry),
      memoryTip: ''
    };

    return wordInfo;
  }

  // 提取音标
  extractPhonetic(entry) {
    // 优先使用带音标的phonetic
    if (entry.phonetic) {
      return entry.phonetic;
    }
    
    // 从phonetics数组中查找
    if (entry.phonetics && entry.phonetics.length > 0) {
      for (const phonetic of entry.phonetics) {
        if (phonetic.text) {
          return phonetic.text;
        }
      }
    }
    
    return '/未知/';
  }

  // 提取音频URL
  extractAudioUrl(entry) {
    if (entry.phonetics && entry.phonetics.length > 0) {
      for (const phonetic of entry.phonetics) {
        if (phonetic.audio) {
          return phonetic.audio;
        }
      }
    }
    return '';
  }

  // 提取释义
  extractMeanings(entry) {
    const meanings = [];
    
    if (entry.meanings && entry.meanings.length > 0) {
      entry.meanings.forEach(meaning => {
        const partOfSpeech = meaning.partOfSpeech || '';
        
        if (meaning.definitions && meaning.definitions.length > 0) {
          meaning.definitions.forEach(definition => {
            meanings.push({
              partOfSpeech: partOfSpeech,
              definition: definition.definition || '',
              example: definition.example || ''
            });
          });
        }
      });
    }
    
    return meanings.length > 0 ? meanings : [{
      partOfSpeech: '',
      definition: '暂无释义',
      example: ''
    }];
  }

  // 提取词源
  extractEtymology(entry) {
    const etymology = [];
    
    if (entry.origin) {
      etymology.push({
        root: 'origin',
        meaning: entry.origin
      });
    }
    
    return etymology;
  }

  // 提取同义词
  extractSynonyms(entry) {
    const synonyms = [];
    
    if (entry.meanings && entry.meanings.length > 0) {
      entry.meanings.forEach(meaning => {
        if (meaning.synonyms && meaning.synonyms.length > 0) {
          synonyms.push(...meaning.synonyms);
        }
        
        if (meaning.definitions && meaning.definitions.length > 0) {
          meaning.definitions.forEach(definition => {
            if (definition.synonyms && definition.synonyms.length > 0) {
              synonyms.push(...definition.synonyms);
            }
          });
        }
      });
    }
    
    // 去重
    return [...new Set(synonyms)];
  }

  // 提取反义词
  extractAntonyms(entry) {
    const antonyms = [];
    
    if (entry.meanings && entry.meanings.length > 0) {
      entry.meanings.forEach(meaning => {
        if (meaning.antonyms && meaning.antonyms.length > 0) {
          antonyms.push(...meaning.antonyms);
        }
        
        if (meaning.definitions && meaning.definitions.length > 0) {
          meaning.definitions.forEach(definition => {
            if (definition.antonyms && definition.antonyms.length > 0) {
              antonyms.push(...definition.antonyms);
            }
          });
        }
      });
    }
    
    // 去重
    return [...new Set(antonyms)];
  }
}

module.exports = DictionaryAPI; 